<template>
  <div>
    <!-- 面包屑导航区 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">
        首页
      </el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片区域 -->
    <el-card>
      <el-row>
        <el-col>
          <el-button
            type="primary"
            style="margin:0"
          >
            添加角色
          </el-button>
        </el-col>
      </el-row>
      <el-table
        :data="rolesList"
        border
        stripe
      >
        <!-- 展开列 -->
        <el-table-column
          type="expand"
          label="展开"
        >
          <template slot-scope="scope">
            <!-- 一级 权限for循环获取 -->
            <el-row
              v-for="(item1 , i1) in scope.row.children"
              :key="item1.id"
              :class="['dbbottom',i1===0 ? 'dbtop':'','vcenter']"
            >
              <el-col :span="5">
                <el-tag
                  closable
                  :disable-transitions="false"
                  @close="removeRightById(scope.row,item1.id)"
                >
                  {{ item1.authName }}
                </el-tag>
                <i class="el-icon-caret-right" />
              </el-col>
              <el-col :span="19">
                <!-- 二级权限for循环获取 -->
                <el-row
                  v-for="(item2 , i2) in item1.children"
                  :key="item2.id"
                  :class="[i2===0 ? '':'dbtop','vcenter']"
                >
                  <el-col :span="6">
                    <el-tag
                      closable
                      type="success"
                      :disable-transitions="false"
                      @close="removeRightById(scope.row,item2.id)"
                    >
                      {{ item2.authName }}
                    </el-tag>
                    <i class="el-icon-caret-right" />
                  </el-col>
                  <el-col :span="18">
                    <!-- 三级权限for循环获取 -->
                    <el-tag
                      v-for="(item3 , i3) in item2.children"
                      :key="item3.id"
                      :class="[i3===0 ? '':'']"
                      closable
                      type="warning"
                      :disable-transitions="false"
                      @close="removeRightById(scope.row,item3.id)"
                    >
                      {{ item3.authName }}
                    </el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
            <!-- <pre>
              {{scope.row}}
            </pre>-->
          </template>
        </el-table-column>
        <el-table-column
          type="index"
          label="序号"
        />
        <el-table-column
          prop="roleName"
          label="角色名称"
        />
        <el-table-column
          prop="roleDesc"
          label="角色描述"
        />
        <el-table-column
          label="操作"
          width="400px"
        >
          <template slot-scope="scope">
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
            >
              编辑
            </el-button>
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
            >
              删除
            </el-button>
            <el-button
              type="warning"
              icon="el-icon-setting"
              size="mini"
              @click="showSetRightDialog(scope.row)"
            >
              分配权限
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <el-dialog
      title="分配权限"
      :visible.sync="setRightDialogVisible"
      width="40%"
      @close="setRightDialogClose"
    >
      <!-- 树形结构权限 -->
      <el-tree
        :data="rightlist"
        :props="treeProps"
        show-checkbox
        default-expand-all
        node-key="id"
        :default-checked-keys="defKeys"
        ref="treeRef"
      />

      <span
        slot="footer"
        class="dialog-footer"
      >
        <el-button @click="setRightDialogVisible = false">取 消</el-button>
        <el-button
          type="primary"
          @click="allotRights"
        >确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
export default {
  data() {
    return {
      // 角色列表数据
      rolesList: [],
      // 隐藏权限列表对话框
      setRightDialogVisible: false,
      // 所有权限数据
      rightlist: [],
      // 树形控件的属性绑定对象
      treeProps: {
        children: 'children',
        label: 'authName'
      },
      // 默认选中的权限id
      defKeys: [],
      // roleId 当前即将分配权限的id
      roleId: ''
    }
  },
  created() {
    // 加载角色列表
    this.getRolesList()
  },
  methods: {
    // 获取角色列表
    async getRolesList() {
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      }
      this.rolesList = res.data
    // console.log(this.rolesList)
    },
    // 根据id删除权限
    async removeRightById(role, itemId) {
      const confirmResult = await this.$confirm('此操作将永久删除该权限, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      if (confirmResult !== 'confirm') {
        return this.$message.info('取消了删除')
      }
      // 请求取消权限
      const { data: res } = await this.$http.delete(`roles/${role.id}/rights/${itemId}`)
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      }
      // 直接赋值给role.children可以防止全局刷新
      role.children = res.data
      this.$message.success(res.meta.msg)
    },
    // 弹出展示有权限对话框
    async showSetRightDialog(role) {
    //  把roleid保存到data中
      this.roleId = role.id
      // 获取所有权限的列表
      const { data: res } = await this.$http.get('rights/tree')
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      }
      this.rightlist = res.data
      // console.log(this.rightlist)
      // 调用获取到的三级节点的id处理函数
      this.getLeafKeys(role, this.defKeys)
      this.setRightDialogVisible = true
    },
    // 通过递归的方式,获取角色三级权限下的id,并保存到defKeys中
    getLeafKeys(node, arr) {
      // 如果当前node不好含children属性,则是三级节点
      if (!node.children) {
        return arr.push(node.id)
      }
      node.children.forEach(item =>
        this.getLeafKeys(item, arr))
    },
    // 关闭dialog时清空默认选中权限列表
    setRightDialogClose() {
      this.defKeys = []
    },
    // 为角色添加权限
    async allotRights() {
      const keys = [
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys()
      ]
      // console.log(keys)
      const idStr = keys.join(',')
      const { data: res } = await this.$http.post(`roles/${this.roleId}/rights`, { rids: idStr })
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      }
      this.$message.success(res.meta.msg)
      this.getRolesList()
      this.setRightDialogVisible = false
    }
  }
}
</script>
<style lang="less" scoped>
// 文字水平居中
   /deep/.el-table th > .cell {

  text-align: center;

}

/deep/.el-table .cell {

  text-align: center;

}
// 按钮间距
.el-button{
  margin:0 15px;
}
// 标签样式修改
.el-tag{
  margin:10px;
}
.dbtop{
border-top: 1px solid #eee;
}
.dbbottom{
  border-bottom: 1px solid #eee;
}
.vcenter{
  display: flex;
  align-items: center;
}
</style>
